package com.woniu.zsd.merchant.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.client.PermissionClient;
import com.woniu.dto.BusinessHoursDto;
import com.woniu.dto.SiteListDto;
import com.woniu.form.*;
import com.woniu.zsd.commons.exception.ZsdException;
import com.woniu.zsd.merchant.entity.Site;
import com.woniu.zsd.merchant.mapper.SiteMapper;
import com.woniu.zsd.merchant.service.ISiteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.zsd.merchant.util.RedisKey;
import com.woniu.zsd.permission.entity.AdminInfo;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-27
 */
@Service
public class SiteServiceImpl extends ServiceImpl<SiteMapper, Site> implements ISiteService {

    @Autowired
    private SiteMapper siteMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private PermissionClient permissionClient;

    @Override
    public Page<SiteListDto> siteList(SiteListForm siteListForm) {

        Page<Site> page = new Page<>(siteListForm.getPageNum() == null ? 1 : siteListForm.getPageNum(),
                                     siteListForm.getPageSize() == null ? 5 : siteListForm.getPageSize());
        QueryWrapper<Site> queryWrapper = new QueryWrapper<>();

        if (siteListForm.getStatus() != null) {
            queryWrapper.eq("status", siteListForm.getStatus());
        }

        if (siteListForm.getName() != null && !siteListForm.getName().isEmpty()) {
            queryWrapper.like("site_name", siteListForm.getName());
        }

        if (siteListForm.getCity() != null && !siteListForm.getCity().isEmpty()){
            queryWrapper.eq("city", siteListForm.getCity());
        }

        if (siteListForm.getDistrict() != null && !siteListForm.getDistrict().isEmpty()){
            queryWrapper.eq("district", siteListForm.getDistrict());
        }

        Page<Site> sitePage = siteMapper.selectPage(page, queryWrapper); // 假设这里没有额外的查询条件

        return (Page<SiteListDto>) sitePage.convert(site -> {
            SiteListDto siteListDto = new SiteListDto();
            BeanUtils.copyProperties(site, siteListDto);

            // 将 businessHours 字符串转换为 List<BusinessHoursDto>
            try {
                if (site.getBusinessHours() != null && !site.getBusinessHours().equals("")){
                    List<BusinessHoursDto> businessHoursList = objectMapper.readValue(site.getBusinessHours(), objectMapper.getTypeFactory().constructCollectionType(List.class, BusinessHoursDto.class));
                    siteListDto.setBusinessHours(businessHoursList);
                }
            } catch (IOException e) {
                throw new RuntimeException("Failed to convert businessHours to List<BusinessHoursDto>", e);
            }

            return siteListDto;
        });
    }

    private void isSite(Integer siteId, String siteUserPhone, String siteName) {
        QueryWrapper<Site> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("site_name", siteName);
        List<Site> sites = siteMapper.selectList(queryWrapper);
        System.out.println("sites:"+sites);
        // 判断数据库如果手机号与 siteUserPhone 不等则抛出异常
        if (!sites.isEmpty()){
            for (Site site : sites){
                // siteId 判断是否是修改还是新增
                if (site.getId() != siteId) {
                    if (site.getSiteName().equals(siteName)) {
                        throw new ZsdException("站点名称已存在", 500);
                    }
                }
            }
        }
    }

    @Override
    public void addSite(AddSiteForm addSiteForm){
        isSite(null, addSiteForm.getSiteUserPhone(), addSiteForm.getSiteName());
        Site site = new Site();
        BeanUtil.copyProperties(addSiteForm, site);
        site.setBusinessHours(JSONUtil.toJsonStr(addSiteForm.getBusinessHours()));
        siteMapper.insert(site);
        //创建时不去修改负责人
//        Integer siteId = site.getId();
//        System.out.println(siteId);
//
//        List<AdminInfo> adminInfos = permissionClient.selAdminInfoById(-1, -1, 1, 10, addSiteForm.getSiteUserPhone()).getData().getList();
//        System.out.println(adminInfos);
// 如果数据库有负责人修改负责人负责的站点，否则添加该用户
//        if (adminInfos.isEmpty()) {
//            System.out.println("添加负责人");
//            AdminInfoForm aif = new AdminInfoForm();
//            aif.setName(addSiteForm.getSiteUserName());
//            aif.setPhone(addSiteForm.getSiteUserPhone());
//            aif.setRole(2);
//            aif.setSiteId(siteId);
//            aif.setUsername(addSiteForm.getSiteUserPhone());
//            System.out.println(aif);
//            permissionClient.insertAdminInfo(aif);
//            System.out.println("添加成功");
//        } else {
//            System.out.println("修改负责人");
//            UpdateAdminInfoForm uaif = new UpdateAdminInfoForm();
//            uaif.setSiteId(siteId);
//            System.out.println(adminInfos.get(0).getAdminId());
//            uaif.setAdminId(adminInfos.get(0).getAdminId());
//            System.out.println(uaif);
//            permissionClient.updateAdminInfo(uaif);
//        }
        redisTemplate.delete(RedisKey.SITE_ALL_KEY());
    }

    @Override
    public void deleteSite(Integer id) {
        siteMapper.deleteById(id);
        redisTemplate.delete(RedisKey.SITE_ALL_KEY());
    }

    @Override
    public void updateSite(UpdateSiteForm updateSiteForm) {
        isSite(updateSiteForm.getId(), updateSiteForm.getSiteUserPhone(), updateSiteForm.getSiteName());
        Site site = new Site();
        BeanUtil.copyProperties(updateSiteForm, site);
        site.setBusinessHours(JSONUtil.toJsonStr(updateSiteForm.getBusinessHours()));
        siteMapper.updateById(site);

//        Integer siteId = site.getId();
//        System.out.println(siteId);

//        List<AdminInfo> adminInfos = permissionClient.selAdminInfoById(-1, -1, 1, 10, site.getSiteUserPhone()).getData().getList();
//        System.out.println(adminInfos);
//        // 如果数据库有负责人修改负责人负责的站点，否则添加该用户
//        if (adminInfos.isEmpty()) {
//            System.out.println("添加负责人");
//            AdminInfoForm aif = new AdminInfoForm();
//            aif.setName(updateSiteForm.getSiteUserName());
//            aif.setPhone(updateSiteForm.getSiteUserPhone());
//            aif.setRole(2);
//            aif.setSiteId(siteId);
//            aif.setUsername(updateSiteForm.getSiteUserPhone());
//            System.out.println(aif);
//            permissionClient.insertAdminInfo(aif);
//            System.out.println("添加成功");
//        } else {
//            System.out.println("修改负责人");
//            UpdateAdminInfoForm uaif = new UpdateAdminInfoForm();
//            uaif.setSiteId(siteId);
//            System.out.println(adminInfos.get(0).getAdminId());
//            uaif.setAdminId(adminInfos.get(0).getAdminId());
//            System.out.println(uaif);
//            permissionClient.updateAdminInfo(uaif);
//        }
    }

    @Override
    public List<Integer> recentSiteId(Double longitude, Double latitude) {

        return siteMapper.recentSiteId(longitude, latitude);
    }

    @Override
    public SiteListDto findSiteById(Integer id) {
        Site site = siteMapper.selectById(id);
        SiteListDto siteListDto = new SiteListDto();
        BeanUtils.copyProperties(site, siteListDto);
        siteListDto.setBusinessHours(JSONUtil.toList(site.getBusinessHours(), BusinessHoursDto.class));

        return siteListDto;
    }

    // Haversine 公式计算两个经纬度之间的距离
    private double calculateDistance(double lon1, double lat1, double lon2, double lat2) {
        final int R = 6371; // 地球半径，单位为公里

        double latDistance = Math.toRadians(lat2 - lat1);
        double lonDistance = Math.toRadians(lon2 - lon1);

        double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);

        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return R * c; // 距离，单位为公里
    }

}